import { createRouter, createWebHashHistory, RouteRecordName, RouteRecordRaw } from 'vue-router'
import { useRouterList } from '../stores/modules/routerList'
import { store } from '@/stores/index'
import { useUserInfo } from '@/stores/modules/userInfo'
import NProgress from '@/plugins/progress'
const { setAuthRouter, setDefaultRouter, removeCacheList } = useRouterList(store)
const modules: Record<string, any> = import.meta.glob(['./modules/**/*.ts'], {
  eager: true
})
/** 原始静态路由（未做任何处理） */
const routes: Array<any> = []

Object.keys(modules).forEach((key) => {
  routes.push(modules[key].default)
})

const remainingPaths: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  }
]

export const router = createRouter({
  history: createWebHashHistory(),
  routes: remainingPaths
})
// 不需要登录的路由白名单
const whiteList = ['/login']
//
let isFirstLoading = true
setDefaultRouter(remainingPaths)
router.beforeEach((to, from) => {
  NProgress.start()
  // 首次进入路由添加动态路由
  if (isFirstLoading && useUserInfo(store).token) {
    routes.forEach((item) => {
      router.addRoute(item)
    })
    // 添加路由后改变状态
    isFirstLoading = false
    setAuthRouter(routes)
    return to.fullPath
  }
  if (whiteList.includes(to.fullPath)) return true
  else if (!useUserInfo(store).token) return { path: '/login' }
  else if (router.hasRoute(to.name as RouteRecordName)) return true
  else
    return router.hasRoute('404' as RouteRecordName)
      ? { name: '404' }
      : { name: remainingPaths[0].name }
})
export const removeRouteList = (): void => {
  removeCacheList().forEach((name) => {
    router.removeRoute(name)
  })
  isFirstLoading = true
  router.push({ name: remainingPaths[0].name })
}
router.afterEach(() => {
  NProgress.done()
})
